import sys
import tkinter as tk

from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout

from api import oksHttp
from config import oksConfig
from tool.log import OkxLogger

import logging

# 配置日志
logging.basicConfig(filename='api.log', filemode='w', level=logging.INFO)
okxLogger = OkxLogger('okx', 'okx.log').get_logger()


class App(QWidget):
    def __init__(self):
        super().__init__()
        self.root = tk.Tk()
        self.initUI()

        self.buyNum = None
        self.instType = None
        self.instId = None
        self.supportLevel = None
        self.profitRate = None

        self.timer = QTimer(self)
        self.waiting_sell = oksConfig.getWaitingSell()
        if self.waiting_sell:
            self.ownCount = oksConfig.getOwnCount()
        else:
            self.ownCount = None

        self.lastTimeMarkPrice = None
        # 购买的币数量

    def initUI(self):
        # 设置窗口标题
        self.setWindowTitle('交易自动化')
        self.resize(1500, 300)  # 设置窗口大小

        # 创建垂直布局
        layout = QVBoxLayout(self)

        # 创建标签和输入框，并添加到布局中
        self.entries = {}
        labels_texts = ["产品类型:", "市场标记:", "查价间隔:", "买入份额:", "支撑位:", "利润率:"]
        default_values = {
            "产品类型:": "MARGIN",
            "市场标记:": "fet-usdt",
            "查价间隔:": "15",  # 以秒为单位
            "买入份额:": "100",
            "支撑位:": "2.15",
            "利润率:": "0.03"
        }

        for label_text in labels_texts:
            label = QLabel(label_text, self)
            layout.addWidget(label)
            entry = QLineEdit(self)
            entry.setText(default_values[label_text])
            layout.addWidget(entry)
            self.entries[label_text] = entry

        # 创建启动和停止按钮，并添加到布局中
        self.start_button = QPushButton('启动', self)
        self.start_button.clicked.connect(self.start_timers)
        layout.addWidget(self.start_button)

        self.stop_button = QPushButton('停止', self)
        self.stop_button.clicked.connect(self.stop_timers)
        layout.addWidget(self.stop_button)

    def check_buy(self):
        print("检查是否买入")
        # oksHttp.buy(instId=instid, sz=num)
        curMarktPrice = oksHttp.getMarkPrice(self.instType, self.instId)
        mSupportLevel = float(self.supportLevel)
        if float(curMarktPrice) > mSupportLevel: #支撑位
            print("价格高于低撑位（" + str(mSupportLevel)+"）： "+  str(float(curMarktPrice))+ "差额："+ str(float(curMarktPrice)-mSupportLevel))
            return

        if curMarktPrice > self.lastTimeMarkPrice:
            # 价格变高，开始买入
            print("当前价格 " + curMarktPrice + " 高于 上次价格 " + self.lastTimeMarkPrice)
            orderId = oksHttp.buy(self.instId, self.buyNum)
            buyAccount = oksHttp.getBuyCount(self.instId, orderId)
            ownAccount = oksHttp.getAccountBalance(self.instId.split("-")[0])
            self.setOwnCount(ownAccount)
            print("投入资金 " + str(self.buyNum) + "买到手 " + str(self.ownCount) + "市场价格为 " + str(curMarktPrice))
            okxLogger.info("投入资金: " + str(self.buyNum) + " 买到手: " + buyAccount + " 市场价格为: " + str(
                curMarktPrice) + " 当前拥有:" + ownAccount)
            self.setWatingSell(True)
        else:
            # 价格走低，继续抄底
            print("当前价格 " + curMarktPrice + " 低于 上次价格 " + self.lastTimeMarkPrice)
        # 不管怎么样，更新上次的价格
        self.lastTimeMarkPrice = curMarktPrice

    def has_profit(self, curMarktPrice):
        #sellPrice = float(self.ownCount) * float(curMarktPrice) * 0.9992
        #手续费:卖出-挂单 0.080%，买入-吃单 0.100%
        sellPrice = float(self.ownCount) * float(curMarktPrice) * (1-0.0008)
        buynum = float(self.buyNum)
        owncount = float(self.ownCount)
        curmarktprice = float(curMarktPrice)
        mProfitRate = float(self.profitRate)
        targetprice = float(self.buyNum) + float( buynum * mProfitRate )
       # if sellPrice < buynum*0.975: #止损 2.5%
        #    print("止损, 售出价格为 " + str(sellPrice) +" 止损价 " + str(buynum*0.975) + " 买入价 " +str(buynum)  + " 差价: " +str(buynum-sellPrice)+ " 持有数量 " +str(owncount) + " 当前市场价 " +str(curmarktprice) )
         #   return True

        if sellPrice > targetprice:
            print("利润正向, 售出价格为 " + str(sellPrice) + " 目标价 " + str(targetprice)+ " 买入价 " + str(buynum) + " 与目标价差价: " + str(
                targetprice - sellPrice) + " 持有数量 " + str(owncount) + " 当前市场价 " + str(curmarktprice))

            return True
        else:
            print("没有利润继续等待, 售出价格为 " + str(sellPrice) + " 目标价 " + str(targetprice)+ " 买入价 " +str(buynum)  + " 与目标价差价: " +str(targetprice-sellPrice)+ " 持有数量 " +str(owncount) + " 当前市场价 " +str(curmarktprice) )
            return False

    def check_sell(self):
        # oksHttp.sell(instId=instid, sz=num)
        print("检查是否卖出")
        curMarktPrice = oksHttp.getMarkPrice(self.instType, self.instId)
        if curMarktPrice > self.lastTimeMarkPrice:
            # 价格变高， 不急着卖出
            print("当前价格 " + curMarktPrice + " 高于 上次价格 " + self.lastTimeMarkPrice)
        else:
            # 价格开始走低，检查是否能够脱手
            print("当前价格 " + curMarktPrice + " 低于 上次价格 " + self.lastTimeMarkPrice)
            if self.has_profit(curMarktPrice):
                # 有利润，可以脱手
                orderId = oksHttp.sell(self.instId, self.ownCount)
                sellPrice = oksHttp.getSellPrice(self.instId, orderId)
                profit = sellPrice - self.buyNum
                print("卖出了， 利润为：" + str(profit))
                okxLogger.info(
                    "卖出了: " + str(self.ownCount) + " 利润为: " + str(profit) + " 市场价为: " + str(curMarktPrice))
                # 充值开始走买入流程
                self.setWatingSell(False)
                self.setOwnCount(None)
        # 不管怎么样，更新上次的价格
        self.lastTimeMarkPrice = curMarktPrice

    def setWatingSell(self, value):
        self.waiting_sell = value
        oksConfig.updateWaitingSell(str(value))

    def setOwnCount(self, value):
        self.ownCount = value
        oksConfig.updateOwnCount(str(value))

    def time_function(self):
        if self.waiting_sell:
            self.check_sell()
        else:
            self.check_buy()

    def start_timers(self):
        print("启动定时器")
        # 获取输入
        self.buyNum = float(self.entries["买入份额:"].text())
        self.instType = self.entries["产品类型:"].text()
        self.instId = self.entries["市场标记:"].text()
        self.supportLevel = self.entries["支撑位:"].text()
        self.profitRate = self.entries["利润率:"].text()

        self.lastTimeMarkPrice = oksHttp.getMarkPrice(self.instType, self.instId)

        buy_interval = int(self.entries["查价间隔:"].text()) * 1000  # 转换为毫秒
        # 启动定时器
        self.timer.timeout.connect(self.time_function)
        self.timer.start(buy_interval)

        self.start_button.setDisabled(True)
        self.stop_button.setEnabled(True)

    def stop_timers(self):
        # 停止定时器
        self.timer.stop()

        self.start_button.setEnabled(True)
        self.stop_button.setDisabled(True)

        print("定时器停止")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())
